package user

import (
	"net/http"
	"strings"

	"oa-rest/common"

	"github.com/gin-gonic/gin"
	"xorm.io/xorm"
)

type AdminUserService struct {
	db *xorm.Engine
}

func NewAdminUserService(db *xorm.Engine) *AdminUserService {
	return &AdminUserService{db: db}
}

// 获取所有用户（admin专用）
func (s *AdminUserService) GetAllUsersHandler(c *gin.Context) {
	var users []UsUser
	err := s.db.Find(&users)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "数据库查询失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": users,
	})
}

// 更新用户状态（启用/禁用）
type UpdateUserStatusRequest struct {
	UserID int64 `json:"userId" binding:"required"`
	Status int32 `json:"status" binding:"required,oneof=1 2"` // 1:启用, 2:禁用
}

func (s *AdminUserService) UpdateUserStatusHandler(c *gin.Context) {
	var req UpdateUserStatusRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误: " + err.Error()})
		return
	}

	// 更新用户状态
	_, err := s.db.ID(req.UserID).Cols("status").Update(&UsUser{Status: req.Status})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "更新用户状态失败: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "用户状态更新成功",
	})
}

// 强制修改密码请求结构
type ForceResetPasswordRequest struct {
	UserID   int64  `json:"userId" binding:"required"`
	Password string `json:"password" binding:"required,min=6"`
}

// 强制修改密码（管理员专用）
func (s *AdminUserService) ForceResetPasswordHandler(c *gin.Context) {
	var req ForceResetPasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误: " + err.Error()})
		return
	}

	// 检查用户是否存在
	var user UsUser
	has, err := s.db.ID(req.UserID).Get(&user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "数据库查询失败: " + err.Error()})
		return
	}
	if !has {
		c.JSON(http.StatusNotFound, gin.H{"code": 404, "msg": "用户不存在"})
		return
	}

	// 加密密码
	encryptedPassword := strings.ToUpper(common.EncodeMD5(req.Password))

	// 更新密码
	_, err = s.db.ID(req.UserID).Cols("password").Update(&UsUser{Password: encryptedPassword})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "密码更新失败: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "密码重置成功",
	})
}

// 添加账户请求结构
type AddUserRequest struct {
	UserName string `json:"userName" binding:"required,min=3,max=50"`
	RealName string `json:"realName" binding:"required,max=50"`
	Password string `json:"password" binding:"required,min=6"`
}

// 添加账户（管理员专用）
func (s *AdminUserService) AddUserHandler(c *gin.Context) {
	var req AddUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误: " + err.Error()})
		return
	}

	// 检查用户名是否已存在
	var existingUser UsUser
	has, err := s.db.Where("user_name = ?", req.UserName).Get(&existingUser)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "数据库查询失败: " + err.Error()})
		return
	}
	if has {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "用户名已存在"})
		return
	}

	// 加密密码
	encryptedPassword := strings.ToUpper(common.EncodeMD5(req.Password))

	// 创建新用户 - 获取最大ID并设置新ID
	var maxId int64
	s.db.SQL("SELECT MAX(id) FROM us_user").Get(&maxId)
	newId := maxId + 1

	newUser := UsUser{
		Id:                  newId, // 手动设置ID避免序列冲突
		UserName:            req.UserName,
		RealName:            req.RealName,
		Password:            encryptedPassword,
		Status:              1,  // 默认启用状态
		Mobile:              "", // 设置空手机号
		FormulaJurisdiction: 0,  // 默认权限
		SignUrl:             "", // 默认签名URL
	}

	// 插入数据库
	_, err = s.db.Insert(&newUser)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "用户创建失败: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "账户添加成功",
	})
}

// 删除用户请求结构
type DeleteUserRequest struct {
	UserID   int64  `json:"userId" binding:"required"`
	Password string `json:"password" binding:"required"` // 管理员密码确认
}

// 删除用户（管理员专用）
func (s *AdminUserService) DeleteUserHandler(c *gin.Context) {
	var req DeleteUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误: " + err.Error()})
		return
	}

	// 获取当前登录的管理员用户信息
	adminUserName, exists := c.Get("username")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "未登录或会话已过期"})
		return
	}

	// 验证管理员密码
	var adminUser UsUser
	has, err := s.db.Where("user_name = ?", adminUserName).Get(&adminUser)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "数据库查询失败: " + err.Error()})
		return
	}
	if !has {
		c.JSON(http.StatusNotFound, gin.H{"code": 404, "msg": "管理员用户不存在"})
		return
	}

	// 验证管理员密码是否正确
	encryptedPassword := strings.ToUpper(common.EncodeMD5(req.Password))
	if adminUser.Password != encryptedPassword {
		c.JSON(http.StatusForbidden, gin.H{"code": 403, "msg": "管理员密码验证失败"})
		return
	}

	// 检查要删除的用户是否存在
	var targetUser UsUser
	has, err = s.db.ID(req.UserID).Get(&targetUser)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "数据库查询失败: " + err.Error()})
		return
	}
	if !has {
		c.JSON(http.StatusNotFound, gin.H{"code": 404, "msg": "要删除的用户不存在"})
		return
	}

	// 不能删除自己
	if targetUser.UserName == adminUserName {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "不能删除当前登录的管理员账户"})
		return
	}

	// 使用事务删除用户及相关数据
	tx := s.db.NewSession()
	defer tx.Close()
	err = tx.Begin()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "事务开始失败: " + err.Error()})
		return
	}

	// 删除用户角色关联
	_, err = tx.Exec("DELETE FROM us_user_role WHERE user_id = ?", req.UserID)
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "删除用户角色关联失败: " + err.Error()})
		return
	}

	// 删除用户组织关联
	_, err = tx.Exec("DELETE FROM us_user_organization WHERE user_id = ?", req.UserID)
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "删除用户组织关联失败: " + err.Error()})
		return
	}

	// 删除用户
	_, err = tx.ID(req.UserID).Delete(&UsUser{})
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "删除用户失败: " + err.Error()})
		return
	}

	err = tx.Commit()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "事务提交失败: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "用户删除成功",
	})
}
